/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Test;

/**
 *
 * @author Administrador
 */
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;

@SuppressWarnings("serial")
public class WaitCursor2 extends JPanel {

    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private JComponent glassPane;
    private JButton runBackgroundProcBtn;
    private JTextArea textarea = new JTextArea(15, 30);

    public WaitCursor2(JComponent glassPane) {
        this.glassPane = glassPane;
        glassPane.setFocusable(true);
        glassPane.addMouseListener(new MouseAdapter() {
        }); // so it will trap mouse events.

        add(new JTextField(10));
        add(runBackgroundProcBtn = new JButton(new AbstractAction(
                "Run Background Process") {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                runBackgroundProcessAction();
            }
        }));
        add(new JScrollPane(textarea));
    }

    private void runBackgroundProcessAction() {
        disableSystem(true);
        glassPane.setVisible(true);
        new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                long sleepTime = 5000;
                Thread.sleep(sleepTime);
                return null;
            }

            @Override
            protected void done() {
                disableSystem(false);
            }
        }.execute();
    }

    public void disableSystem(boolean disable) {
        glassPane.setVisible(disable);
        runBackgroundProcBtn.setEnabled(!disable);
        if (disable) {
            System.out.println("started");
            glassPane.requestFocusInWindow(); // so can't add text to text components
            glassPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        } else {
            System.out.println("done");
            glassPane.setCursor(Cursor.getDefaultCursor());
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("WaitCursor2");
        WaitCursor2 mainPanel = new WaitCursor2((JComponent) frame.getGlassPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGui();
            }
        });
    }
}
